# home_design的序列化器
from rest_framework import serializers

from users.serializers import UserSerializer
from .models import Inspiration, Image, InspirationComment, InspirationFavorite, StyleFavorite, InspirationVoting, \
    Style, StyleVoting, StyleComment

"""_________________________________图片_________________________________"""


class ImageSerializer(serializers.ModelSerializer):
    class Meta:
        model = Image
        fields = ['id', 'inspiration', 'style', 'image', 'uploaded_at']
        read_only_fields = ('id',)

    def to_representation(self, instance):
        representation = super().to_representation(instance)
        if 'image' in representation:
            representation['image'] = instance.image.url  # 返回相对路径
        return representation


"""_________________________________全局灵感_________________________________"""


class InspirationSerializer(serializers.ModelSerializer):
    images = ImageSerializer(many=True, read_only=True)  # 用于获取灵感时显示图片信息
    uploaded_images = serializers.ListField(
        child=serializers.ImageField(max_length=100000, allow_empty_file=False, use_url=False),
        write_only=True
    )  # 用于创建灵感时上传图片

    class Meta:
        model = Inspiration
        fields = ['id', 'inspiration_classification', 'big_name', 'small_name', 'big_description', 'small_description',
                  'created_at', 'images', 'uploaded_images']
        read_only_fields = ('id',)

    def create(self, validated_data):
        uploaded_images = validated_data.pop('uploaded_images', [])

        # 在保存灵感之前，设置设计师为当前用户
        validated_data['designer'] = self.context['request'].user

        inspiration = Inspiration.objects.create(**validated_data)

        # 创建关联的图片对象
        for image in uploaded_images:
            Image.objects.create(inspiration=inspiration, image=image)

        return inspiration


class InspirationListSerializer(serializers.ModelSerializer):
    images = ImageSerializer(many=True, read_only=True)  # 用于获取灵感时显示图片信息
    designer = UserSerializer()
    uploaded_images = serializers.ListField(
        child=serializers.ImageField(max_length=100000, allow_empty_file=False, use_url=False),
        write_only=True
    )  # 用于创建灵感时上传图片
    is_favorited = serializers.SerializerMethodField() # 用于显示灵感是否被收藏
    is_voting = serializers.SerializerMethodField() # 用于显示灵感是否被投票
    vote_count = serializers.SerializerMethodField()  # 用于显示灵感的投票数量

    class Meta:
        model = Inspiration
        fields = '__all__'
        read_only_fields = ('id',)

    def get_is_favorited(self, obj):
        user = self.context.get('request').user
        if not user.is_authenticated:
            return 0
        return 1 if InspirationFavorite.objects.filter(user=user, inspiration=obj,
                                                       inspiration_favorite_status=1).exists() else 0

    def get_is_voting(self, obj):
        user = self.context.get('request').user
        if not user.is_authenticated:
            return 0
        return 1 if InspirationVoting.objects.filter(user=user, inspiration=obj,
                                                     inspiration_voting_status=1).exists() else 0

    def get_vote_count(self, obj):
        """
        获取灵感的投票数量
        """
        return obj.voted_by.filter(inspiration_voting_status=1).count()


class InspirationCommentCrateSerializer(serializers.ModelSerializer):
    # 用于获取评论时显示评论者信息
    class Meta:
        model = InspirationComment
        fields = ['inspiration', 'content', 'created_at']
        read_only_fields = ('id',)

    def create(self, validated_data):
        request = self.context.get('request')
        validated_data['user'] = request.user
        return super().create(validated_data)


class InspirationCommentSerializer(serializers.ModelSerializer):
    inspiration = InspirationSerializer()
    user = UserSerializer()

    class Meta:
        model = InspirationComment
        fields = '__all__'
        read_only_fields = ('id',)


class InspirationFavoriteSerializer(serializers.ModelSerializer):
    class Meta:
        model = InspirationFavorite
        fields = ['id', 'inspiration', 'created_at']
        read_only_fields = ('id',)

    def create(self, validated_data):
        request = self.context.get('request')
        validated_data['user'] = request.user
        return super().create(validated_data)


class InspirationFavoriteListSerializer(serializers.ModelSerializer):
    inspiration = InspirationSerializer()
    user = UserSerializer()

    class Meta:
        model = InspirationFavorite
        fields = '__all__'
        read_only_fields = ('id',)


class InspirationVotingSerializer(serializers.ModelSerializer):
    class Meta:
        model = InspirationVoting
        fields = ['id', 'inspiration', 'created_at']
        read_only_fields = ('id',)

    def create(self, validated_data):
        request = self.context.get('request')
        validated_data['user'] = request.user
        return super().create(validated_data)


"""_________________________________单品_________________________________"""


class StyleSerializer(serializers.ModelSerializer):
    images = ImageSerializer(many=True, read_only=True)  # 用于获取灵感时显示图片信息
    uploaded_images = serializers.ListField(
        child=serializers.ImageField(max_length=100000, allow_empty_file=False, use_url=False),
        write_only=True
    )  # 用于创建灵感时上传图片

    class Meta:
        model = Style
        fields = ['id', 'style_classification', 'name', 'material', 'size',
                  'color', 'design_concept', 'process_overview', 'created_at', 'images', 'uploaded_images']
        read_only_fields = ('id',)

    def create(self, validated_data):
        uploaded_images = validated_data.pop('uploaded_images', [])

        # 在保存设计之前，设置设计师为当前用户
        validated_data['designer'] = self.context['request'].user

        style = Style.objects.create(**validated_data)

        # 创建关联的图片对象
        for image in uploaded_images:
            Image.objects.create(style=style, image=image)

        return style


class StyleListSerializer(serializers.ModelSerializer):
    images = ImageSerializer(many=True, read_only=True)  # 用于获取灵感时显示图片信息
    designer = UserSerializer()
    uploaded_images = serializers.ListField(
        child=serializers.ImageField(max_length=100000, allow_empty_file=False, use_url=False),
        write_only=True
    )  # 用于创建灵感时上传图片
    is_favorited = serializers.SerializerMethodField()
    is_voting = serializers.SerializerMethodField()
    vote_count = serializers.SerializerMethodField()  # 用于显示灵感的投票数量


    class Meta:
        model = Style
        fields = '__all__'
        read_only_fields = ('id',)

    def get_is_favorited(self, obj):
        user = self.context.get('request').user
        if not user.is_authenticated:
            return 0
        return 1 if StyleFavorite.objects.filter(user=user, style=obj,
                                                 style_favorite_status=1).exists() else 0

    def get_is_voting(self, obj):
        user = self.context.get('request').user
        if not user.is_authenticated:
            return 0
        return 1 if StyleVoting.objects.filter(user=user, style=obj,
                                               style_voting_status=1).exists() else 0

    def get_vote_count(self, obj):
        """
        获取灵感的投票数量
        """
        return obj.voted_by.filter(style_voting_status=1).count()


class StyleCommentCreateSerializer(serializers.ModelSerializer):
    class Meta:
        model = StyleComment
        fields = ['style', 'content', 'created_at']
        read_only_fields = ('id',)

    def create(self, validated_data):
        user = self.context.get('request').user
        validated_data['user'] = user
        return super().create(validated_data)


class StyleCommentSerializer(serializers.ModelSerializer):
    style = StyleSerializer()
    user = UserSerializer()

    class Meta:
        model = StyleComment
        fields = '__all__'
        read_only_fields = ('id',)


class StyleFavoriteSerializer(serializers.ModelSerializer):
    style = StyleSerializer()
    user = UserSerializer()

    class Meta:
        model = StyleFavorite
        fields = '__all__'
        read_only_fields = ('id',)


class StyleVotingSerializer(serializers.ModelSerializer):
    style = serializers.CharField(max_length=100)
    user = UserSerializer()

    class Meta:
        model = StyleVoting
        fields = '__all__'
        read_only_fields = ('id',)
